package main

import (
	"fmt"
	"sort"
)

func main() {
	people := []int{3, 2, 2, 1}
	limit := 3
	fmt.Println(numRescueBoats(people, limit))
}

//#link: https://leetcode-cn.com/problems/boats-to-save-people/
func numRescueBoats(people []int, limit int) (ans int) {
	sort.Ints(people)
	index := sort.SearchInts(people, limit+1)
	if index < len(people) {
		ans += len(people) - index - 1
	}
	begin, end := 0, index
	if index >= len(people) {
		end--
	}
	for begin <= end {
		sum := people[begin] + people[end]
		if sum <= limit {
			begin++
		}
		end--
		ans++
	}
	return ans
}
